<template>
    <page-box class="custom-page-box">
        <template v-slot:header>
            <ask-breadcrumb>
                <template v-for="(item, index) in $getBreadCrumbsName($route.path)">
                    <ask-breadcrumb-item :key="index" v-if="item.path" :to="'/' + item.path">{{ item.meta.title }}</ask-breadcrumb-item>
                    <ask-breadcrumb-item :key="index" v-else>{{ item.meta.title }}</ask-breadcrumb-item>
                </template>
            </ask-breadcrumb>
        </template>
        <div class="userList-table-container">
            <page-search>
                <page-search-column class="fixed-column">
                    <page-search-item>
                        <el-date-picker
                            class="pbb__search-input date"
                            v-model="form.createTime"
                            type="daterange"
                            @change="handleTime"
                            range-separator="~"
                            start-placeholder="开始创建日期"
                            :clearable="false"
                            end-placeholder="结束创建日期">
                        </el-date-picker>
                    </page-search-item>
                    <page-search-item>
                        <el-tabs v-model="activeName" @tab-click="handleTabClick" class="date-select">
                            <el-tab-pane label="今天" name="1" />
                            <el-tab-pane label="昨天" name="2" />
                            <el-tab-pane label="最近一周" name="3" />
                            <el-tab-pane label="最近一个月" name="4" />
                        </el-tabs>
                    </page-search-item>
                </page-search-column>
            </page-search>
            <div class="e-chart-box">
                <div class="mission-rank">
                    <p class="e-c-b-title">任务数排名</p>
                        <div class="e-chart" ref="missionRank"></div>
                </div>
                <div class="mission-statistics">
                    <p class="e-c-b-title">本村任务统计</p>
                    <div>
                        <div class="e-chart" ref="missionStatistics" v-show="taskStatistic"></div>
                        <div v-if="taskStatistic">
                            <p>任务数：</p>
                            <p>{{taskStatistic.total}}条</p>
                            <p>进行中

                                <el-popover
                                    popper-class="overview-warning-popover"
                                    placement="top-start"
                                    trigger="hover"
                                    content="当前时间仍未完成的任务"
                                    :visible-arrow="false"
                                >
                                    <i class="el-icon-warning" slot="reference"></i>
                                </el-popover>


                                ：</p>
                            <p>{{taskStatistic.incomplete}}条</p>
                            <p>已完成：</p>
                            <p>{{taskStatistic.complete}}条</p>
                        </div>
                    </div>
                </div>
                <div class="amount-rank">
                    <p class="e-c-b-title">数据量排名<span>包含未提交数据</span></p>
                    <div class="e-chart" ref="amountRank"></div>
                </div>
            </div>
            <p class="title">完成任务排名</p>
            <div class="overview-table-box">
                <el-table
                    border
                    ref="multipleTable"
                    :data="tableData"
                    class="pbb__table"
                    header-cell-class-name="pbb__table-thead"
                    cell-class-name="pbb__table-thead-cell"
                    row-class-name="pbb__table-thead-row"
                    style="width: 100%;height: calc(100% - 58px);overflow-y: auto;">
                    <el-table-column
                        label="排名"
                        align="center"
                        type="index"
                        width="60">
                    </el-table-column>
                    <el-table-column
                        label="姓名"
                        prop="name">
                    </el-table-column>
                    <el-table-column
                        label="完成任务数(条) "
                        prop="complete">
                    </el-table-column>
                    <el-table-column prop="incomplete">
                        <template slot="header">
                            进行中任务数(条)
                            <el-popover
                                popper-class="overview-warning-popover"
                                placement="top-start"
                                trigger="hover"
                                content="当前时间仍未完成的任务"
                                :visible-arrow="false"
                            >
                                <i class="el-icon-warning" slot="reference"></i>
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="采集数据-包含未提交数量(条)"
                        prop="data">
                    </el-table-column>
                </el-table>
            </div>
        </div>
    </page-box>
</template>

<script lang="ts">
import { Component, Mixins } from "vue-property-decorator";
import dayjs from 'dayjs';
import EchartsMixin from "@/mixins/echarts.mixin";

interface UnknownData{
    [propsName: string]: any;
}


@Component({
    name: "OverviewNotAlive"
})
export default class Overview extends Mixins(EchartsMixin) {
    tableData: UnknownData[] =[]
    dataRanking: UnknownData[] =[]
    taskRanking: UnknownData[] =[]
    taskStatistic: UnknownData[] =[]


    created() {
        this.getChart();
        this.getTable();
    }


    async getChart() {
        let { createTime } = this.form;
        createTime = createTime.map(item => dayjs(item).format('YYYY-MM-DD'));

        const rs = await this.$server["overview/getChart"]({
            data: {
                startTime: createTime[0] || "",
                endTime: createTime[1] || ""
            }
        });
        this.dataRanking = rs.data.data.dataRanking;
        this.taskRanking = rs.data.data.taskRanking;
        this.taskStatistic = rs.data.data.taskStatistic;
        this.$nextTick(() => {
            this.missionRankChart();
            this.missionStatisticsChart();
            this.amountRankChart();
        });
    }

    async getTable() {
        let { createTime } = this.form;
        createTime = createTime.map(item => dayjs(item).format('YYYY-MM-DD'));

        const rs = await this.$server["overview/getTable"]({
            data: {
                startTime: createTime[0] || "",
                endTime: createTime[1] || ""
            }
        });
        this.tableData = rs.data.data;
    }

    // mixins中handleTabClick的补充
    handleTabClickExtend(): void {
        this.getChart();
        this.getTable();
    }


    handleTime(): void {
        this.activeName = '';
        this.getChart();
        this.getTable();
    }


    // 任务数排名e-charts数据处理
    missionRankChart(): void {
        const chartData = this.taskRanking;

        const xAxisData: string[] = [];
        const incomplete: UnknownData = {
            name: '进行中',
            key: 'incomplete',
            data: [],
            type: 'bar',
            stack: 'a',
            itemStyle: {
                color: '#2C50C9'
            },
            label: {
                show: true,
                fontSize: 12,
                color: '#fff',
                formatter(item: UnknownData) {
                    return item.data === 0 ? '' : item.data;
                }
            }
        };
        const complete: UnknownData = {
            name: '已完成',
            key: 'incomplete',
            data: [],
            type: 'bar',
            stack: 'a',
            itemStyle: {
                color: '#32A78F'
            },
            label: {
                show: true,
                fontSize: 12,
                color: '#000',
                formatter(item: UnknownData) {
                    return item.data === 0 ? '' : item.data;
                }
            }
        };
        const total: UnknownData = {
            name: '总计',
            key: 'total',
            data: [],
            type: 'bar',
            stack: '',
            z: -1,
            barGap: '-100%',
            itemStyle: {
                color: 'transparent'
            },
            label: {
                show: true,
                position: 'top',
                padding: [0, 0, 8, 0],
                color: '#000',
                formatter(item: UnknownData) {
                    return item.data === 0 ? '' : item.data;
                }
            }
        };
        chartData.forEach(item => {
            xAxisData.push(item.name);
            incomplete.data.push(item.incomplete);
            complete.data.push(item.complete);
            total.data.push(item.total);
        });

        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: { // 坐标轴指示器，坐标轴触发有效
                    type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                }
            },
            legend: {
                data: ['进行中', '已完成'],
                right: '16',
                top: '0'
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: [
                {
                    type: 'category',
                    axisLine: {
                        lineStyle: {
                            color: '#909399'
                        }
                    },
                    axisLabel: {
                        rotate: 45
                    }
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    axisTick: { // y轴刻度线
                        show: false
                    },
                    splitLine: { // 网格线
                        show: true,
                        lineStyle: {
                            color: "#E4E7ED",
                            opacity: 0.5
                        }
                    },
                    axisLine: {
                        show: false,
                        lineStyle: {
                            color: '#909399'
                        }
                    }
                }
            ]
        };
        const optionChange = {
            xAxis: [
                {
                    data: xAxisData
                }
            ],
            series: [incomplete, complete, total]
        };

        this.setEcharts('missionRank', option, optionChange, (charts: UnknownData) => {
            charts.on('legendselectchanged', function() {
                try {
                    const currentOption = charts.getOption();
                    const selected = currentOption.legend[0].selected;
                    let flag = false;
                    if (selected) {
                        flag = Object.values(selected).some((item: unknown) => item === false);
                    }


                    currentOption.series = currentOption.series.map((item: UnknownData) => {
                        if (item.key === 'total') {
                            item.label.show = !flag;
                        }
                        return item;
                    });
                    charts.setOption(currentOption, true);

                    // if (flag) {
                    //     currentOption.series = currentOption.series.filter((item: any) => (item.key !== 'total'));
                    //     charts.setOption(currentOption, true);
                    // } else {
                    //     charts.setOption(merge(true, option, optionChange), true);
                    // }
                } catch (e) {
                    console.log(e);
                }
            });
        });
    }

    // 本村任务统计e-charts数据处理
    missionStatisticsChart(): void {
        const chartData: UnknownData = this.taskStatistic;

        const option = {
            tooltip: {
                trigger: 'item'
            },
            series: [
                {
                    name: '任务状态',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '20',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    }
                }
            ]
        };
        const optionChange = {
            series: [
                {
                    label: {
                        formatter(params: UnknownData) {
                            let str = '';
                            const item = params.data;
                            try {
                                str = `{a|${item.name}}\n`;
                                str += `{b|${item.value}条(${params.percent}%)}`;
                            } catch (e) {}
                            return str;
                        },
                        rich: {
                            a: {
                                fontSize: 28,
                                lineHeight: 41,
                                color: '#101010'
                            },
                            b: {
                                fontSize: 12,
                                lineHeight: 17,
                                color: 'rgb(16, 16, 16)'
                            }
                        }
                    },
                    data: [
                        {
                            value: chartData ? chartData.incomplete : '',
                            name: '进行中',
                            itemStyle: {
                                color: '#2C50C9'
                            }
                        },
                        {
                            value: chartData ? chartData.complete : '',
                            name: '已完成',
                            itemStyle: {
                                color: '#32A78F'
                            }
                        }
                    ]
                }
            ]
        };

        this.setEcharts('missionStatistics', option, optionChange, (myChart: UnknownData) => {
            const index = chartData.incomplete ? 0 : 1;
            myChart.dispatchAction({
                type: 'downplay',
                seriesIndex: 0
            });
            myChart.dispatchAction({
                type: 'highlight',
                seriesIndex: 0,
                dataIndex: index
            });

            myChart.on('mouseover', (e: UnknownData) => {
                // 鼠标滑入取消整个系列高亮
                myChart.dispatchAction({
                    type: 'downplay',
                    seriesIndex: e.seriesIndex
                });
                // 然后高亮鼠标悬停的那块
                myChart.dispatchAction({
                    type: 'highlight',
                    dataIndex: e.dataIndex
                });
            });

            // 监听鼠标滑出事件
            myChart.on('mouseout', (e: UnknownData) => {
                // 鼠标滑出取消整个系列所有高亮
                myChart.dispatchAction({
                    type: 'downplay',
                    seriesIndex: e.seriesIndex
                });
                // 然后高亮鼠标最后悬停的那块
                myChart.dispatchAction({
                    type: 'highlight',
                    dataIndex: e.dataIndex
                });
            });
        });
    }

    // 数据量排名e-charts数据处理
    amountRankChart(): void{
        const chartData = this.dataRanking;

        const xAxisData: string[] = [];
        const total: UnknownData = {
            name: '数据量',
            key: 'total',
            type: 'bar',
            itemStyle: {
                color: '#2C50C9'
            },
            label: {
                show: true,
                position: 'top',
                fontSize: 12,
                color: '#000',
                formatter(item: UnknownData) {
                    return item.data === 0 ? '' : item.data;
                }
            },
            data: []
        };
        chartData.forEach((item) => {
            xAxisData.push(item.name);
            total.data.push(item.total);
        });
        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: [
                {
                    type: 'category',
                    axisLine: {
                        lineStyle: {
                            color: '#909399'
                        }
                    },
                    axisLabel: {
                        rotate: 45
                    }
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    axisTick: { // y轴刻度线
                        show: false
                    },
                    splitLine: { // 网格线
                        show: true,
                        lineStyle: {
                            color: "#E4E7ED"
                        }
                    },
                    axisLine: {
                        show: false,
                        lineStyle: {
                            color: '#909399'
                        }
                    }
                }
            ]
        };
        const optionChange = {
            xAxis: [{
                data: xAxisData
            }],
            series: [total]
        };

        this.setEcharts('amountRank', option, optionChange);
    }
}
</script>
<style lang="scss">

.overview-warning-popover{
    border: 1px solid #dcdfe6!important;
}
</style>
<style lang="scss" scoped>
::v-deep{
    .page-base-body{
        height: calc(100% - 50px)!important;
    }
    .el-tabs__nav-wrap::after{
        display: none;
    }
    .el-tabs__item:focus-visible{
      outline: none!important;
    }
}
.custom-page-box{
    .overview-table-box{
        padding: 0 20px 30px;
        background-color: #fff;
    }
    .title{
        padding: 30px 20px 20px;
        margin: 0;
        line-height: 1;
        background-color: #fff;
    }

    .e-c-b-title{
        span{
            font-size: 12px;
            color: rgb(125, 120, 120);
            margin-left: 10px;
        }
    }

    .date-select{
        margin-left: 10px;
        ::v-deep{
            .el-tabs__item{
                height: 36px;
                line-height: 36px;
            }
            .el-tabs__header{
               margin-bottom: 0;
            }
        }

    }
    .e-chart-box{
        margin: 10px 0;
        display: flex;
        &>div{
            flex: 1;
        }
        &>div:nth-child(1){
            padding-right: 8px;
        }
        &>div:nth-child(2){
            padding-right: 8px;
            padding-left: 8px;
        }
        &>div:nth-child(3){
            padding-left: 8px;
        }
        .e-chart{
            width: 100%;
            height: 280px;
            background-color: #fff;
        }
        .e-c-b-title{
            background-color: #fff;
            line-height: 1;
            padding: 10px;
            margin: 0;
        }
        .mission-statistics{
            background-color: #fff;
            &>div{
                display: flex;
                p{
                    width: 80px;
                    font-size: 14px;
                    color: rgb(16, 16, 16);
                    line-height: 1;
                }
                p:nth-child(even){
                    color: rgb(104, 102, 102);
                }
                p:nth-child(2),p:nth-child(4){
                    margin-bottom: 40px;
                }
                &>div:nth-child(2){
                    padding-top: 25px;
                }
            }
        }
    }
}

</style>
